package com.wits.qso.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.web.controller.BaseController;
import com.wits.qso.entity.Btable;
import com.wits.qso.entity.Cls;
import com.wits.qso.entity.Course;
import com.wits.qso.entity.Croom;
import com.wits.qso.entity.Dept;
import com.wits.qso.entity.Grade;
import com.wits.qso.entity.Teacher;
import com.wits.qso.service.BtableDaoService;
import com.wits.qso.service.ClsService;
import com.wits.qso.service.CourseService;
import com.wits.qso.service.CroomService;
import com.wits.qso.service.DeptService;
import com.wits.qso.service.GradeService;
import com.wits.qso.service.StudentService;
import com.wits.qso.service.TeacherService;
import com.wits.qso.service.YearService;

@Controller
@RequestMapping(value="qso/btable")
public class BtableController extends BaseController {

	/**
	 * 注入BtableService
	 */
	@Autowired
	private BtableDaoService btableDaoService;
	/**
	 * 注入教室service
	 */
	@Autowired
	private CroomService croomService;
	/**
	 * 注入课程service
	 */
	@Autowired
	private CourseService courseService;

	/**
	 * 注入科系Service
	 */
	@Autowired
	private DeptService deptService;

	/**
	 * 注入教师Service
	 */
	@Autowired
	private TeacherService teacherService;
	/**
	 * 注入班级Service
	 */
	@Autowired
	private ClsService clsService;
	/**
	 * 注入年级Service
	 */
	@Autowired
	private GradeService gradeService;
	/**
	 * 注入studentService
	 */
	@Autowired
	private StudentService studentService;
	/**
	 * 注入studentService
	 */
	@Autowired
	private YearService yearService;
	/**
	 * 基本课表列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/toList")
	public String toList(Model model){
		List<Croom> rooms=croomService.findAll();

		Calendar cal=Calendar.getInstance();
		
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		Date monday=cal.getTime();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		Date sunday=cal.getTime();
		
		String jsons="";
		
		if(rooms.size()>0){
			Croom room=rooms.get(0);
			jsons=btableDaoService.getDataByRoom(room.getCrmId(), monday, sunday);
		}
		model.addAttribute("roomlist", rooms);
		model.addAttribute("jsons", jsons);
		return "qso/btable/list";
	}
	
	@RequestMapping(value="/listjson")
	@ResponseBody
	public String toListJson(Model model,@RequestParam String roomid){

		String json="";
		
		Calendar cal=Calendar.getInstance();
		
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		Date monday=cal.getTime();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		Date sunday=cal.getTime();
		
		if(roomid==""){
			List<Croom> rooms=croomService.findAll();
			model.addAttribute("rooms", rooms);
			if(rooms.size()>0){
				Croom room=rooms.get(0);
				json=btableDaoService.getDataByRoom(room.getCrmId(), monday, sunday);
			}
		}else{
			Croom room=croomService.getOne(roomid);
			json=btableDaoService.getDataByRoom(room.getCrmId(), monday, sunday);
		}

		return json;
	}
	
	/**
	 * 新增
	 * @param model
	 * @param id 基本课表编号
	 * @return
	 */
	@RequestMapping(value="/add")
	public String toAdd(Model model,@RequestParam String id){
		Btable bt=btableDaoService.getOne(id);
		List<Btable> btList=btableDaoService.findByWedayAndClass(bt.getWeday(), bt.getCalss(),bt.getCrmid());
		
		List<Teacher> teaList= teacherService.findAll();
		List<Cls> clsList=clsService.findAll();
		
		if(bt.getTeaid()==null && bt.getClaid()==null)
		if(btList!=null && btList.size()>0){
			for(int i=0;i<btList.size();i++){
				Btable ta=btList.get(i);
				if(ta.getTeaid()!=null){
					if(teaList.indexOf(ta.getTeaid())>-1)
						teaList.remove(teaList.indexOf(ta.getTeaid()));
				}	
				if(ta.getClaid()!=null){
					if(clsList.indexOf(ta.getClaid())>-1)
					clsList.remove(clsList.indexOf(ta.getClaid()));
				}
			}
		}
		model.addAttribute("courses", courseService.findAll());
		model.addAttribute("depts", deptService.findAll());
		model.addAttribute("teachers",teaList);
		model.addAttribute("grades", gradeService.findAll());
		model.addAttribute("clas", clsList);
		model.addAttribute("id",id);
		model.addAttribute(WebConstants.COMMAND,bt);
		return "qso/btable/form";
	}

	/**
	 * 新增
	 * @param model
	 * @param id 基本课表编号
	 * @return
	 */
	@RequestMapping(value="/newadd")
	public String toNewAdd(Model model,@RequestParam String id){
		List<Course> courses= courseService.findAll();
		List<Dept> depts= deptService.findAll();
		List<Teacher> teachers= teacherService.findAll();
		List<Grade> grades= gradeService.findAll();
		List<Cls> clses= clsService.findAll();
		model.addAttribute("courses", courses);
		model.addAttribute("depts", depts);
		model.addAttribute("teachers", teachers);
		model.addAttribute("grades", grades);
		model.addAttribute("clas", clses);
		model.addAttribute("id",id);
		
		Croom room=croomService.getOne(id);
		List<Btable> bts=btableDaoService.findIsSettedByCroom(room);
		Set<Integer> set=new HashSet<Integer>();
		for(int i=0;i<bts.size();i++){
			Btable bt=bts.get(i);
			set.add((Integer.parseInt(bt.getCalss())-1)*7+Integer.parseInt(bt.getWeday())-2);
		}
		String tbValues="";
		for(int i=0;i<70;i++){
			boolean flag=false;
			for (Integer integer : set) {
				if(integer==i) {
					flag=true;
					break;
				}
			}
			tbValues+=flag+",";
			
		}
		
		List<Integer> indexList=new ArrayList<Integer>();
		for(int k=0;k<room.getCrmClassNum();k++){
			int t=room.getWeekT(),f=room.getWeekF();
			boolean t1=false,t2=false;
			
			if(t==1){
				if(f==1){
					indexList.add((k+1)*7-1);
				}else{
					for(int l=2;l<=f;l++){
						indexList.add(k*7+l-2);
					}
					indexList.add((k+1)*7-1);
				}
			}else{
				if(f==1){
					for(int l=t;l<=7;l++){
						indexList.add(k*7+l-2);
					}
					indexList.add((k+1)*7-1);
				}else{
					for(int l=t;l<=f;l++){
						indexList.add(k*7+l-2);
					}
				}
			}
		}
		
		tbValues=tbValues.substring(0, tbValues.length()-1);
		String[] strList=tbValues.split(",");
		
		JSONArray strJson=new JSONArray();
		for(int i=0;i<strList.length;i++){
			strJson.add(i,strList[i]);
		}
		
		JSONArray indexJson=new JSONArray();
		for(int i=0;i<indexList.size();i++){
			indexJson.add(i,indexList.get(i));
		}
		//table的数据列表
		model.addAttribute("strJson",strJson);
		model.addAttribute("indexJson",indexJson);
		return "qso/btable/newform";
	}

	/**
	 * 
	 * @param model
	 * @param command
	 * @param viewType
	 * @param id 按课程添加的时候为教室id，否则为课节id
	 * @param courseId
	 * @param dptId
	 * @param teaId
	 * @param gradeId
	 * @param classId
	 * @param values
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/save",method={RequestMethod.POST})
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Btable command,
			@RequestParam String viewType,@RequestParam String id,
			@RequestParam String courseId,@RequestParam String dptId,
			@RequestParam String teaId,@RequestParam String gradeId,
			@RequestParam String classId,@RequestParam String values,
			BindingResult result,
			HttpServletRequest req){

		try {
			List<Btable> bts=null;
			List<List<Btable>> list=null;
			List<List<Btable>> delList=null;
			
			if(values==""){
				list=new ArrayList<List<Btable>>();
				Btable btable=btableDaoService.getOne(id);
				bts=btableDaoService.findByCroom(btable.getCrmid(), btable.getWeday(), btable.getCalss());
				list.add(bts);
			}else{
				list=new ArrayList<List<Btable>>();
				delList=new ArrayList<List<Btable>>();
				Croom cr=null;
				String tempValues=values.substring(0, values.length()-1);
				String[] tempArrary=tempValues.split(",");
				for (int i = 0; i < tempArrary.length; i++) {
					cr=croomService.getOne(id);
					String web=getWedayStr(i);
					String cal=getCalssStr(i);
					bts=btableDaoService.findByCroom(cr, web, cal);
					if(bts!=null && bts.size()>0){
						if(Boolean.parseBoolean(tempArrary[i].toString())){
							list.add(bts);
						}else{
							delList.add(bts);
						}
					}
				}
			}
			//保存选中的课程
			for(int k=0;k<list.size();k++){
				List<Btable> tt=list.get(k);
				for(int i=0;i<tt.size();i++){
					Btable bt=tt.get(i);
					//判断同一时间段同一班级不能在不同的教室上课。
					if(btableDaoService.isEixtClass(clsService.getOne(classId), bt.getTime_start(), bt.getTime_end())){
						return ajaxDoneError("同一时间段同一班级不能在不同的教室上课");
					}
					bt.setCouid(courseService.getOne(courseId));
					bt.setDptid(deptService.getOne(dptId));
					bt.setTeaid(teacherService.getOne(teaId));
					bt.setGradeid(gradeService.getOne(gradeId));
					bt.setClaid(clsService.getOne(classId));
					bt.setDateUpd(new Date());
					bt.setUserUpd(getCurrentUserId());
					btableDaoService.save(bt);
				}
			}

			return ajaxDoneSuccess(this.getText("save.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}

	/**
	 * 获取当前是星期几,星期的取值范围为1-7,星期一:2,星期二:3,星期三:4,星期四5,星期五:6,星期六:7,星期日:1
	 * @param index
	 * @return
	 */
	private String getWedayStr(int index){
		int key=index%7;
		String result="";
		if(key==6) result=1+"";
		else result=key+2+"";
		return result;
	}

	/**
	 * 获取当前是第几节，课节的取值范围为1-10
	 * @param index
	 * @return
	 */
	private String getCalssStr(int index){
		int key=index/7;
		return (key+1)+"";
	}
	
}
